import { NextResponse, type NextRequest } from 'next/server'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { commerceDb } from '@/app/lib/commerce-db'; import { isAdmin } from '@/app/lib/admin'; import { prodigiFetch } from '@/app/lib/prodigi'; import { prodigiItem } from '@/app/lib/prodigi-skus'; import { sendEmail } from '@/app/lib/email'; import { env } from '@/app/lib/env'; import { displayOrderId } from '@/app/lib/orders'; import { inProductionHtml } from '@/app/lib/order-emails'; import { generateMagicLink } from '@/app/lib/magic-link'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; // Admin-triggered "send to printer" step. Customer approval moves the // order to `approved` but does NOT auto-fire the Prodigi order — admin // always does one final review (right print file, right shipping // address, no oddities) and clicks this route to commit. On success // the order moves to `in_production` and the customer gets the // "your portrait is on its way to print" email. export async function POST( req: NextRequest, ctx: { params: Promise<{ id: string }> }, ) { const { id } = await ctx.params; const user = await getCustomerUser(); if (!user || !isAdmin(user.email)) { return NextResponse.json({ error: 'forbidden' }, { status: 403 }); } const admin = commerceDb(); const { data: order } = await admin .from('orders') .select('id, user_email, status, config, shipping_address, prodigi_order_id, current_generation_id') .eq('id', id) .single(); if (!order) return NextResponse.json({ error: 'order not found' }, { status: 404 }); if (order.status !== 'approved') { return NextResponse.json({ error: `Cannot send to printer — order status is "${order.status}". This action only works after the customer has approved their proof (status: approved).`, }, { status: 409 }); } if (order.prodigi_order_id) { return NextResponse.json({ error: `This order already has a Prodigi reference (${order.prodigi_order_id}). Refusing to create a duplicate.`, }, { status: 409 }); } // Look up the published generation's clean URL (Prodigi prints this). const proofQuery = admin .from('generations') .select('clean_url') .eq('order_id', id); const { data: pubGen } = await (order.current_generation_id ? proofQuery.eq('id', order.current_generation_id) : proofQuery.eq('published', true)).single(); if (!pubGen?.clean_url) { return NextResponse.json({ error: 'No published generation found for this order. Publish a proof first.', }, { status: 409 }); } // Resolve the SKU + colour/wrap attributes from the customer's config. const cfg = order.config as { productId: 'matted' | 'canvas' | 'classic' | 'stretched'; size: string; frame: string; matteId?: string; wrap?: string; }; const { sku, attributes } = prodigiItem({ productId: cfg.productId, sizeId: cfg.size, frameId: cfg.frame, matteId: cfg.matteId, wrapId: cfg.wrap, }); // Build the Prodigi recipient block from the shipping address Stripe // collected at checkout. Without it we can't print — fail fast. type ShippingAddr = { name?: string; address?: { line1?: string; line2?: string | null; city?: string; state?: string; postal_code?: string; country?: string; }; }; const shipping = order.shipping_address as ShippingAddr | null; if (!shipping?.name || !shipping.address?.line1) { return NextResponse.json({ error: 'Shipping address is missing on this order — cannot send to print without it.', }, { status: 409 }); } const recipient = { name: shipping.name, address: { line1: shipping.address.line1, line2: shipping.address.line2 ?? undefined, townOrCity: shipping.address.city, stateOrCounty: shipping.address.state, postalOrZipCode: shipping.address.postal_code, countryCode: shipping.address.country, }, }; // Create the Prodigi order. let prodigiOrderId: string | null = null; try { const prodigiRes = await prodigiFetch('Orders', { method: 'POST', body: JSON.stringify({ shippingMethod: 'Standard', recipient, items: [{ sku, copies: 1, sizing: 'fillPrintArea', attributes, assets: [{ printArea: 'default', url: pubGen.clean_url }], }], callbackUrl: `${env.site.url()}/api/webhooks/prodigi/${process.env.PRODIGI_WEBHOOK_TOKEN}`, }), }); const prodigiJson = await prodigiRes.json() as { order?: { id?: string }; outcome?: string }; if (!prodigiRes.ok || !prodigiJson.order?.id) { console.error('[send-to-printer] Prodigi rejected', prodigiRes.status, prodigiJson); return NextResponse.json({ error: `Prodigi rejected the order (${prodigiRes.status}): ${prodigiJson?.outcome ?? 'unknown error'}. Nothing was charged or shipped; the order stays at "approved" so you can retry.`, }, { status: 502 }); } prodigiOrderId = prodigiJson.order.id; } catch (e) { console.error('[send-to-printer] Prodigi error', e); const msg = e instanceof Error ? e.message : 'Prodigi request failed'; return NextResponse.json({ error: `Prodigi request failed: ${msg}. Order stays at "approved" — try again.`, }, { status: 502 }); } // Commit the transition. await admin.from('orders').update({ status: 'in_production', prodigi_order_id: prodigiOrderId, }).eq('id', id); // Customer confirmation email — magic-link to the order page so // they land signed in if they click through. const reviewPath = `/orders/${id}#review`; const orderLink = await generateMagicLink(order.user_email, reviewPath); const fallbackUrl = `${env.site.url()}${reviewPath}`; await sendEmail({ to: order.user_email, subject: `In production — ${displayOrderId(id)}`, html: inProductionHtml(id, orderLink ?? fallbackUrl, prodigiOrderId), text: `Your portrait is on its way to print. We'll email you again when it ships. Once it arrives, you can leave a star rating, write a review, and share a photo from your order page. View your order: ${orderLink ?? fallbackUrl}`, }).catch(() => {}); return NextResponse.json({ ok: true, prodigiOrderId }); }